package io.github.quickmsg.interate.sharedstrategy;

import cn.hutool.core.collection.ListUtil;
import org.apache.commons.lang3.tuple.ImmutableTriple;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinStrategy  implements  SharedStrategy{
    private final AtomicInteger sequence = new AtomicInteger();
    @Override
    public ImmutableTriple<String, String, String> searchSharedSubscribe(Set<ImmutableTriple<String, String, String>> shareSubscribes, String consistentId) {
        List<ImmutableTriple<String, String, String>> subscribes = ListUtil.toList(shareSubscribes);
        int length = subscribes.size();
        return subscribes.get(getPositiveSequence() % length);
    }

    private int getPositiveSequence() {
        for (; ; ) {
            int current = sequence.get();
            int next = current >= Integer.MAX_VALUE ? 0 : current + 1;
            if (sequence.compareAndSet(current, next)) {
                return current;
            }
        }
    }
}
